package com.protocolo;

import java.io.IOException;


public class Encriptacion {

	/**
	 *Metodo que permite encriptar un determinado string utilizando una clave para dicha encriptacion
	 * @param string
	 * @param clave
	 * @return
	 */
	public static String Encript64(String string,String clave){
		String result = new String("");
		char[] temp,cl;
		char dato;
		temp = string.toCharArray();
		cl = clave.toCharArray();
		int num=0,indice=0;
		for (int i=0;i<string.length();i++){
			indice = i % clave.length()+1;									
			num =(int)(temp[i]) ^ (int)(indice==clave.length()?0:cl[indice]);					
			dato = (char) num;
			result +=String.valueOf(dato);
		}
		result=base64_encode(result);        
		return result;

	}
	
	public static String base64_encode(String text){
		//sun.misc.BASE64Encoder base64 = new sun.misc.BASE64Encoder();
		//Base64 base64 = new Base64();
		byte[] pwhash = text.getBytes(); 
		
		String result =new  String(Base64.encodeBytes(pwhash));
		return result;
	}
	
	/**
	 * Metodo que permite desencriptar un string por medio de la palabra clave por la que se encripto
	 * @param string
	 * @param clave
	 * @return
	 */
	public static String Decrypt64(String string,String clave){
		String result = new String("");
		char[] temp,cl;
		char dato;
		int num=0,indice=0;
		string=base64_decode(string);
		temp = string.toCharArray();
		cl = clave.toCharArray();		
		for (int i=0;i<string.length();i++){
			indice = i % clave.length()+1;									
			num =(int)(temp[i]) ^ (int)(indice==clave.length()?0:cl[indice]);					
			dato = (char) num;
			result +=String.valueOf(dato);
		}			
		return result;
	}
		
	public static String base64_decode(String text) {
		//sun.misc.BASE64Decoder base64 = new sun.misc.BASE64Decoder();
//		BASE64Decoder base64 = new BASE64Decoder();
		String result="";
		try {
			result = new  String(Base64.decode(text));
		} catch (IOException e) {
	
		}
		return result;
	}
}